<template>
    <div class="list">
        <el-tabs type="card" class="latest">
            <el-tab-pane label="最近">
                <ul>
                    <v-contextmenu ref="context">
                        <v-contextmenu-item @click="handleDelete(1)">删除</v-contextmenu-item>
                    </v-contextmenu>
                    <div v-for="item in sessions" v-contextmenu:context @contextmenu.prevent="rightClick(item.id)"
                    >
                    <li style="list-style-type:none"
                        :class="{ active: item.id === currentId }" @click="selectSession(item.id)" :key="item.id">
                        <img class="avatar" width="30" height="30"  :src="item.user.img">
                        <div v-if="item.ifOnline" class="status"></div>
                        <div v-else class="status-offline"></div>
                        <p class="name">{{ item.user.name }}</p>
                        <div v-if="item.redFlag" class="redPoint"></div>
                    </li>
                    </div>
                </ul>
            </el-tab-pane>
            <el-tab-pane label="医院">
                <el-tree class="tree-list" :data=hospitalList node-key="id" @node-click="selectPerson">
                    <template #default="{ node, data }">
                        <div class="custom-tree-node">
                            <img class="avatar" v-if="data.avatar!=null" width="20" height="20" :src="data.avatar">
                            <div v-if="data.avatar" class="status-offline"></div>
                            <span>{{ node.label }}</span>
                        </div>
                    </template>
                </el-tree>
            </el-tab-pane>
            <el-tab-pane label="群聊">
              <div>
              <el-button class="build-group" @click="addGroup">创建群聊   <i class="el-icon-lx-add"></i></el-button>
              </div>
                <ul>
                    <li style="list-style-type:none" v-for="item in groups"
                        :class="{ active: item.id === groupId }" @click="selectGroup(item.id)" :key="item.id">
                        <img class="avatar" width="30" height="30" src="src/assets/img/pig.jpg">
                        <p class="name">{{ item.name }}</p>
                    </li>
                </ul>
            </el-tab-pane>
        </el-tabs>

        <!-- 新增弹窗 -->
        <el-dialog title="添加群聊" v-model="addVisible" :destroy-on-close="false" width="35em" center>
            <el-form label-width="5em" style="width: 90%">
                <el-form-item label="群聊名称">
                    <el-input maxlength="10" show-word-limit  v-model.trim="newGroup.name"/>
                </el-form-item>

                <el-form-item label="选择成员">
                    <el-tree ref="treeRef"
                             class="select-tree"
                             :data=selectList
                             show-checkbox
                             node-key="id"
                             highlight-current>
                        <template #default="{ node, data }">
                            <div class="custom-tree-node">
                                <img class="avatar" v-if="data.avatar!=null" width="20" height="20" :src="data.avatar">
                                <span>{{ node.label }}</span>
                            </div>
                        </template>
                    </el-tree>
                </el-form-item>
                <el-form-item label="群 公 告">
                    <el-input maxlength="20" show-word-limit  v-model.trim="newGroup.notice"/>
                </el-form-item>
            </el-form>

        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false" size="small">取消</el-button>
                    <el-button type="primary" size="small" @click="addSave()">确定</el-button>
                </span>
        </template>
      </el-dialog>
    </div>
</template>

<script>
import {useStore} from 'vuex';
import {reactive, computed,ref} from "vue";
import {getOnline, getAllHistory} from "../api/chat";
import {ElMessage} from "element-plus";
import {findPerson} from "../utils/find";

export default {
    setup() {
        let store = useStore()

        let addVisible = ref(false);

        //初始化
        let sessionList = computed(() => store.state.sessions)
        let hospitalList=computed(() => store.state.usersList)
        let selectList=hospitalList.value.slice(1,3);
        let groups=computed(() => store.state.groups)
        //右键索引，初始为-1
        let contextMenuIndex='-1'

        //在最近聊天列表右键
        let rightClick=(index)=>{
            contextMenuIndex=index;
        }

        //删除最近聊天列表
        let handleDelete = () => {
            store.commit('DELETE_SESSION', contextMenuIndex);
        }

        let selectSession = (id) => {
            console.log("点击事件：",id)
            store.commit('SELECT_SESSION', id);
        }

        let selectPerson = (data) => {
            store.commit('SELECT_PERSON', data.id);
        }

        let selectGroup=(id)=>{
            store.commit('SELECT_GROUP', id);
        }

        let newGroup= ref({
            id: 1,
            name: '',
            owner: store.state.userId,
            time: '',
            notice: '',
            members: [],
        });

        const treeRef = ref();

        //点击添加群组
        let addGroup=()=>{
          addVisible.value=true;
        }

        //保存添加群组
        let addSave = () => {
            newGroup.value.id=groups.value.length+1
            newGroup.value.time=new Date()
            let groupUsers=treeRef.value.getCheckedKeys(false)
            for(let i in groupUsers){
                if(groupUsers[i]!='-1'){
                    let newPerson=findPerson(groupUsers[i])
                    newGroup.value.members.push({
                        id:newPerson.id,
                        name:newPerson.name,
                        avatar:newPerson.avatar
                    })
                }
            }
            store.commit('ADD_GROUP',newGroup.value)
            addVisible.value=false;
        }

        //从接口获取在线userId
        let onlineID = reactive([])

        //定时器判断在线情况
        // setInterval(() => {
        //     //处理部分
        //     ifOnline()
        // }, 3000)
        //判断是否在线
        const ifOnline = async () => {
            await getOnline()
              .then((res) => {
                  if (res.code === 0) {
                      onlineID = res.data
                  } else {
                      ElMessage.error('获取在线ID失败，请稍后重试！');
                  }
              })
              .catch(() => {
                  ElMessage.error('服务器未启动或其他错误！');
              })
            sessionList.value.forEach(element => {
                Object.assign(element, {'ifOnline': false});
                onlineID.forEach(item => {
                    if (parseInt(item) == element.id) element.ifOnline = true
                })
            });
        }
        //聊天记录
        getAllHistory(sessionStorage.getItem('ms_psd')).then((res) => {
            let history = res.data
            let userId = parseInt(sessionStorage.getItem('ms_psd'))
            for (let key in history) {
                let index = sessionList.value.findIndex((item) => {
                    return item.id == key
                })
                if (index != -1) {
                    history[key].forEach((item) => {
                        sessionList.value[index].messages.unshift({
                            content: item.content,
                            date: item.time,
                            type:item.type,
                            self: parseInt(item.from) == userId ? true : false
                        })
                    })
                }
            }
        })
        return {
            sessions:computed(() => store.state.sessions),
            currentId: computed(() => store.state.sessionId),
            groups,
            groupId:computed(()=>store.state.groupId),
            hospitalList,
            selectList,
            treeRef,
            addVisible,
            onlineID,
            newGroup,
            selectSession,
            selectPerson,
            selectGroup,
            addGroup,
            addSave,
            handleDelete,
            rightClick,
        };
    }
}
</script>

<style>
.el-tabs__header{
}

.el-tabs__nav-wrap {
    border-color:  #9ea09e !important;
}
.el-tabs--card>.el-tabs__header .el-tabs__nav {
    border-color: #9ea09e;
    border-left:none;
    border-right:none;
    border-top-left-radius: 0%;
    border-top-right-radius: 0%;
}

.el-tabs__item{
    width:83px;
    color: white !important;
    border-color: #9ea09e !important;
    text-align: center;
}

.is-active {
    color: deepskyblue !important;
    background-color: #9ea09e;
    border-bottom-color: white !important;
}

.latest {
    width: 100%;
}

.latest el-tabs__active-bar {
    background: transparent;
}

.list li {
    padding: 12px 15px;
    border-bottom: 1px solid #757373;
    cursor: pointer;
    transition: background-color .1s;
}

.list:hover {
    background-color: rgba(255, 255, 255, 0.03);
}

.list .active {
    background-color: rgba(255, 255, 255, 0.1);
}

.avatar, .name {
    vertical-align: middle;
}

.avatar {
    border-radius: 2px;
}

.name {
    display: inline-block;
    margin: 0 0 0 15px;
}

.tree-list {
    color: white;
    background-color: #2e3238;
}

.select-tree {
}

.el-tree-node__content {
    padding: 6px 10px;
}

.el-tree-node__content:hover {
    background-color: rgba(255, 255, 255, 0.03) !important;
}

.el-tree-node.is-current > .el-tree-node__content {
    background-color: rgba(255, 255, 255, 0.03) !important;
}

.status {
    display: inline-block;
    margin-left: 5px;
    width: 9px;
    height: 9px;
    background: #6bd382;
    border-radius: 50%;
}

.status-offline {
    display: inline-block;
    margin-left: 5px;
    margin-bottom: 2px;
    width: 9px;
    height: 9px;
    background: #9ea09e;
    border-radius: 50%;
}

.redPoint {
    float:right;
    margin-left: 5px;
    margin-top: 9px;
    width: 9px;
    height: 9px;
    background: red;
    border-radius: 50%;
}

.build-group {
    color: #5d5e6d;
}

</style>